package cn.sofwin.day0328;

public class ChiefAndEater {
    static boolean hasFood = false;
    public static void main(String[] args) {
        Thread chief = new Thread(new Cook());
        Thread eater1 = new Thread(new Eat(), "1");
        Thread eater2 = new Thread(new Eat(), "2");

        chief.start();
        eater1.start();
        eater2.start();
    }
    static class Cook implements Runnable{
        @Override
        public void run() {
            while(true) go();
        }
        private void go(){
            synchronized (ChiefAndEater.class) {
                if (hasFood) return;
                try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
                System.out.println("饭好了");
                hasFood = true;
            }
        }
    }
    static class Eat implements Runnable{
        @Override
        public void run() {
            while(true) go();
        }
        private void go(){
            String name = Thread.currentThread().getName();
            synchronized (ChiefAndEater.class) {
                if (!hasFood) return;
                try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); }
                System.out.println(name + "吃完了");
                hasFood = false;
            }
        }
    }
}
